package com.moon.game.util;

import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.beanutils.BeanUtils;

public class Utils {
	public static <T> String join(Iterable<T> values, String separator) {
		if (values == null)
			return "";
		Iterator<T> iter = values.iterator();
		if (!iter.hasNext())
			return "";
		StringBuffer toReturn = new StringBuffer(String.valueOf(iter.next()));
		while (iter.hasNext()) {
			toReturn.append(separator + String.valueOf(iter.next()));
		}
		return toReturn.toString();
	}

	public static String join(String[] values, String separator) {
		return (values == null) ? "" : join(Arrays.asList(values), separator);
	}

	public static String join(Annotation[] values, String separator) {
		return (values == null) ? "" : join(Arrays.asList(values), separator);
	}

	/**
	 * for java.util.Map
	 */
	public static class Maps {
		public static void mergeValueInMap(Map<String, String[]> map,
				String name, String value) {
			String[] newValues = null;
			String[] oldValues = map.get(name);
			if (oldValues == null) {
				newValues = new String[1];
				newValues[0] = value;
			} else {
				newValues = new String[oldValues.length + 1];
				System.arraycopy(oldValues, 0, newValues, 0, oldValues.length);
				newValues[oldValues.length] = value;
			}
			map.put(name, newValues);
		}

		public static void mergeValueInMap(Map<String, String[]> map,
				String name, String[] values) {
			for (String value : values) {
				mergeValueInMap(map, name, value);
			}
		}

		public static <K, V> Map<K, V> filterMap(Map<K, V> map,
				String keypattern) {
			try {
				@SuppressWarnings("unchecked")
				Map<K, V> filtered = map.getClass().newInstance();
				for (Map.Entry<K, V> entry : map.entrySet()) {
					K key = entry.getKey();
					if (key.toString().matches(keypattern)) {
						filtered.put(key, entry.getValue());
					}
				}
				return filtered;
			} catch (Exception iex) {
				return null;
			}
		}
	}

	/**
	 * 通用翻页函数
	 **/
	public static List<Object> page(List<?> objs, int pageId, int pageSize) {
		if (objs == null) {
			objs = new LinkedList<Object>();
		}
		int start = pageId * pageSize;
		int end = start + pageSize;
		if (start < 0)
			start = 0;
		if (start > objs.size())
			start = objs.size();
		if (end < start)
			end = start;
		if (end > objs.size())
			end = objs.size();

		List<Object> list = new LinkedList<Object>();
		list.addAll(objs.subList(start, end));
		return list;
	}
	
	/**
	 * 计算总的页数 
	 **/
	public static int totalPage(int total, int pageSize){
		int n = total/pageSize;
		if(total%pageSize >0 ){
			n += 1;
		}
		return n;
	}
	
	/**
	 * 适用于本游戏以id:pro|id:pro为格式的概率计算，计算随机后的结果返回字符串
	 * 
	 * @param value 需要计算的字符串
	 * @param base 概率基数
	 * @param times 随机次数
	 * @return 返回随机好的道具及其数量，格式id:num|id:num
	 */
	public static String calculateProbability(String value, int base, int times) {
		LinkedHashMap<String, String> idForArea = handerValueToMap(value);
		if (times <= 0) {
			//错误次数
			return "";
		}
		Random random = new Random();
		String result = "";
		ConcurrentHashMap<Integer, Integer> idNums = new ConcurrentHashMap<Integer, Integer>();
		//随机概率
		for (int i = 0; i < times; i++) {
			int pro = random.nextInt(base);
			for (Map.Entry<String, String> entry : idForArea.entrySet()) {
				if (proInArea(entry.getValue(), pro)) {
					int key = Integer.parseInt(entry.getKey());
					if (idNums.keySet().contains(key)) {
						int num = idNums.get(key).intValue() + 1;
						idNums.put(key, num);
					}else {
						idNums.put(key, 1);
					}
					break;
				}
			}
		}
		for (Map.Entry<Integer, Integer> entry : idNums.entrySet()) {
			result += "|" + entry.getKey() + ":" + entry.getValue() ;
		}
		if (!"".equals(result)) {
			result = result.substring(1, result.length());
		}
		return result;
	}
	
	/**
	 * 检测pro是否包含在以min-max次格式的概率字符串中
	 * 
	 * @param value
	 * @param pro
	 * @return true包含，false不包含
	 */
	public static boolean proInArea(String value, int pro) {
		String[] area = value.split("[-]");
		Integer min = Integer.parseInt(area[0]);
		Integer max = Integer.parseInt(area[1]);
		if (min == null || max == null) {
			return false;
		}
		if (pro >= min.intValue() && pro <= max.intValue()) {
			return true;
		}
		return false;
	}
	
	
	/**
	 * 传入以id:pro|id:pro为格式的概率字符串，返回id对应概率区域的map
	 * 
	 * @param value
	 * @return
	 */
	public static LinkedHashMap<String, String> handerValueToMap(String value) {
		String[] cells = value.split("[|]");
		//记录id和区域的对应关系
		LinkedHashMap<String, String> idForArea = new LinkedHashMap<String, String>();
		int startPlace = 0;
		for (String cell : cells) {
			if (cell == null || cell.length() < 2) {
				continue;
			}
			String[] idPro = cell.split("[:]");
			//记录概率区域
			String proArea = "";
			if (idForArea.size() != 0) {
				Object[] areas = idForArea.values().toArray();
				String[] n = String.valueOf(areas[idForArea.size() - 1]).split("[-]");
				startPlace = Integer.parseInt(n[1]) + 1;
			}
			proArea = startPlace + "-" + (startPlace + Integer.parseInt(idPro[1]));
			idForArea.put(idPro[0], proArea);
		}
		return idForArea;
	}
	
	/*public static void main(String[] args) {
		String value = "1010:30|1119:10|1124:10|1142:10|1143:10";
		calculateProbability(value, 100, 10);
	}*/
	public static void copyProperties(Object dst, Object res) {
		try {
			BeanUtils.copyProperties(dst, res);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 解析字符串，字符串格式a:b|c:d
	 * 
	 * @param info
	 * @return
	 */
	public static HashMap<Integer, Integer> analyzeString(String info) {
		HashMap<Integer, Integer> value = new HashMap<Integer, Integer>();
		String[] n = info.split("[|]");
		for (String cell : n) {
			if (cell != null && cell.length() > 2 && cell.indexOf(":") != -1) {
				String[] d = cell.split("[:]");
				value.put(Integer.parseInt(d[0]), Integer.parseInt(d[1]));
			}
		}
		return value;
	}
	
	/**
	 * 解析简单字符串格式【id|id】
	 * 
	 * @param info
	 * @return
	 */
	public static List<Integer> analyzeSimpleString(String info) {
		List<Integer> value = new ArrayList<Integer>();
		String[] ids = info.split("[|]");
		for (String id : ids) {
			if (id != null && id.length() > 0) {
				value.add(Integer.parseInt(id));
			}
		}
		return value;
	}
}
